plugins {
    id 'java'
    id 'idea'
    id 'com.bmuschko.izpack' version '3.0'// это для плагина izpack
    id 'org.sonarqube' version '3.3'
    id 'checkstyle'
    id 'jacoco'
    id "io.freefair.lombok" version "6.0.0-m2"
    /*jdk12*/
    id 'org.openjfx.javafxplugin' version '0.0.10'
    /**/
}
apply(from: 'nb.gradle')

group 'ru.apertum.qsystem'
version "${appVersion}"

allprojects {
    sourceCompatibility = JavaVersion.VERSION_16
    targetCompatibility = JavaVersion.VERSION_16
    [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
}

String version_properties_file = "${rootDir}/src/main/resources/ru/apertum/qsystem/common/version.properties"

configurations {
    File file = new File(version_properties_file)
    if (!file.exists()) {
        println("File does not exist: " + file.getCanonicalPath())
        boolean created = file.createNewFile()
        if (created) {
            println("File was created: " + file.getCanonicalPath())
        } else {
            println("ERROR. File was not created: " + file.getCanonicalPath())
        }
    }
    feelInfoFile(file)
}

tasks.withType(Tar) {
    enabled = false
}

tasks.withType(Zip) {
    enabled = true
}

test {
    enabled = true
    useTestNG()
}

task branch() {
    println 'BRANCH: "' + getCurrentGitBranch() + '"'
}

project.tasks["sonarqube"].dependsOn "jacocoTestReport"

jacocoTestReport {
    dependsOn test // tests are required to run before generating the report
    reports {
        xml.enabled true
        xml.outputLocation = file("${project.buildDir}/jacoco/jacoco.xml")
    }
}

jacoco {
    toolVersion = "0.8.7"
    //reportsDir = file("$buildDir/customJacocoReportDir")
}

sonarqube {
    properties {
        property "sonar.branch.name", getCurrentGitBranch()
        property "sonar.sourceEncoding", "UTF-8"
        property "sonar.host.url", "https://sonarcloud.io"
        property "sonar.projectKey", "Apertum_qsystem"
        property "sonar.organization", "apertum-bitbucket"
        property "sonar.login", "69c19eaeafee46dcbe5d8daf58edd5e54468af71"
        property "sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/jacoco/jacoco.xml"
        property "sonar.exclusions", "**/*Test.java,**/*Test??.java"
        property "sonar.coverage.exclusions", "**/*Test.java,**/*Test??.java"
        property "sonar.java.binaries", sourceSets.main.output.classesDirs
    }
}

checkstyle {
    toolVersion '8.42'
    configFile file("${rootDir}/gradle/checkstyle/google_checks.xml")
}

checkstyleMain {
    source = 'src/main/java'
    exclude '**/*Test??.java'
    exclude '**/*Test.java'
}
checkstyleTest {
    enabled = false
    source = 'src/test/java'
}

// это для плагина izpack, просто нужно чтоб работал плагин, т.е. настройки и параметры
izpack {
    baseDir = file("installation")
    installFile = file('installation/install.xml')
    outputFile = file("installation/install.jar")
    compression = 'deflate'
    compressionLevel = 9

    appProperties = ['app.group': group, 'app.name': 'QSystem', 'app.title': 'QMS QSystem', 'app.version': version, 'app.subpath': "QSystem-$version"]
}

wrapper {
    gradleVersion = '7.1.1' // Желаемая версия
}

/*jdk12*/
//mainClassName = 'ru.apertum.qsystem.client.fx.Desktop'
// https://gluonhq.com/products/javafx/ - тут все либи для скачивания отдельно.
javafx {
    version = "16"
    modules = ['javafx.controls', 'javafx.fxml', 'javafx.base', 'javafx.graphics', 'javafx.media', 'javafx.swing', 'javafx.web']
    // если локально установленный фреймворк, типа зависимости не подтягиваем, а смотрим в папку с SDK.
    if (version == "10") {
        configuration = 'compileOnly'
        sdk = '/path/to/javafx-sdk'
    }
}
/**/

//*****************************************************************************
//******   VERSION   *****************************************************
//*****************************************************************************

def feelInfoFile(File file) {
    println("Autogenerated by gradle: " + file.toPath())
    if (file.exists()) {
        Properties props = new Properties()
        props.load(new FileInputStream(file))

        print 'Prepare data... '
        props.date = new Date().format("dd.MM.yyyy")
        println(props.date)

        String bld = props.build
        int bldNum = 0
        if (bld != null && bld.matches("\\d+")) {
            bldNum = Integer.parseInt(bld)
        }
        props.build = '' + ++bldNum
        props.version = '' + version
        props.version_db = '' + "${dbVersion}"
        props.name = String.format('' + "${appDescription}", version)
        println('Program version: ' + version)
        println('Build version: ' + props.build)

        FileOutputStream outputStream = new FileOutputStream(file)
        props.store(outputStream, 'Filled out by gradle')
        outputStream.flush()
        outputStream.close()

    } else {
        version = '2.0-SNAPSHOT'
    }
}

def getCurrentGitBranch() {
    def gitBranch = "unknown_branch"
    try {
        def workingDir = new File("${project.projectDir}")
        def result = 'git rev-parse --abbrev-ref HEAD'.execute(null, workingDir)
        result.waitFor()
        if (result.exitValue() == 0) {
            gitBranch = result.text.trim()
        }
    } catch (exception) {
        print exception
    }
    return gitBranch
}

//*****************************************************************************
//******   COMMON   *****************************************************
//*****************************************************************************

repositories {
    mavenCentral()
    // You may define additional repositories, or even remove "mavenCentral()".
    // Read more about repositories here:
    //   http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:repositories
    maven {
        url "https://plugins.gradle.org/m2/"
    }

    flatDir {
        dirs 'lib'
    }
}

dependencies {
    implementation project(":QResources")

    implementation 'org.projectlombok:lombok:1.18.20'
    compileOnly 'org.projectlombok:lombok:1.18.20'
    annotationProcessor 'org.projectlombok:lombok:1.18.20'

    // это для плагина izpack
    izpack('org.codehaus.izpack:izpack:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-ant:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-core:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-panel:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-api:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-compiler:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-dist:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-gui:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-native:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-native-parent:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-tools:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-util:5.1.3') { transitive = true }
    izpack('org.codehaus.izpack:izpack-event:5.1.3') { transitive = true }

    /*jdk12*/
    implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1'
    implementation('org.glassfish.jaxb:jaxb-runtime:2.3.4')
    /**/

    // https://mvnrepository.com/artifact/com.formdev/flatlaf
    //runtimeOnly group: 'com.formdev', name: 'flatlaf', version: '1.5'
    //implementation group: 'com.formdev', name: 'flatlaf-swingx', version: '1.5'
    //implementation group: 'com.formdev', name: 'flatlaf-extras', version: '1.5'
    //implementation group: 'com.formdev', name: 'flatlaf-intellij-themes', version: '1.5'


    implementation(group: 'org.jdesktop', name: 'appframework', version: '1.0.3')
    implementation(group: 'org.netbeans.external', name: 'AbsoluteLayout', version: 'RELEASE111')
    implementation(group: 'com.toedter', name: 'jcalendar', version: '1.4')

    testImplementation 'org.testng:testng:7.4.0'
    testImplementation 'org.mockito:mockito-core:3.11.2'
    testImplementation 'org.mockito:mockito-inline:3.11.2'
    testImplementation group: 'org.powermock', name: 'powermock-module-testng', version: '2.0.9'
    testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9'

    testImplementation group: 'io.cucumber', name: 'cucumber-testng', version: '5.2.0'
    testImplementation group: 'io.cucumber', name: 'cucumber-java', version: '5.2.0'

    implementation fileTree(dir: 'lib', include: '**/*.jar')

    implementation(group: 'mysql', name: 'mysql-connector-java', version: '8.0.17') { transitive = false }
    implementation(group: 'com.h2database', name: 'h2', version: '1.4.197') { transitive = false }

    implementation(group: 'org.hibernate', name: 'hibernate-c3p0', version: '5.3.6.Final') {
        transitive = true
        exclude group: 'dom4j'
    }
    implementation(group: 'org.hibernate', name: 'hibernate-core', version: '5.3.6.Final') {
        transitive = true
        exclude group: 'dom4j'
    }
    implementation(group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.2.Final') { transitive = false }

    implementation(group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.17.0') { transitive = false }
    implementation(group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.17.0') { transitive = false }
    implementation(group: 'org.apache.logging.log4j', name: 'log4j-slf4j18-impl', version: '2.17.0') { transitive = false }

    implementation(group: 'org.dom4j', name: 'dom4j', version: '2.1.1') { transitive = false }
    implementation(group: 'org.reflections', name: 'reflections', version: '0.9.11') { transitive = false }
    implementation(group: 'com.lowagie', name: 'itext', version: '2.1.7') { transitive = false }
    implementation(group: 'net.java.dev.beansbinding', name: 'beansbinding', version: '1.2.1') { transitive = false }
    implementation(group: 'net.sourceforge.barbecue', name: 'barbecue', version: '1.5-beta1') { transitive = false }
    implementation(group: 'com.google.zxing', name: 'core', version: '3.4.1') { transitive = false }

    implementation(group: 'commons-collections', name: 'commons-collections', version: '3.2.2') { transitive = false }
    implementation(group: 'commons-logging', name: 'commons-logging', version: '1.2') { transitive = false }
    implementation(group: 'commons-pool', name: 'commons-pool', version: '1.6') { transitive = false }
    implementation(group: 'org.apache.commons', name: 'commons-lang3', version: '3.7') { transitive = false }
    implementation(group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.3') { transitive = false }
    implementation(group: 'commons-digester', name: 'commons-digester', version: '2.1') { transitive = false }
    implementation(group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4') { transitive = false }
    implementation(group: 'org.apache.commons', name: 'commons-configuration2', version: '2.2') { transitive = false }
    implementation(group: 'commons-codec', name: 'commons-codec', version: '1.11') { transitive = false }
    implementation(group: 'commons-cli', name: 'commons-cli', version: '1.4') { transitive = false }
    implementation(group: 'org.apache.commons', name: 'commons-jexl3', version: '3.1') { transitive = false }


    implementation(group: 'jfree', name: 'jcommon', version: '1.0.16') { transitive = false }
    implementation(group: 'jfree', name: 'jfreechart', version: '1.0.13') { transitive = false }

    implementation(group: 'javax.help', name: 'javahelp', version: '2.0.05') { transitive = false }

    implementation(group: 'com.googlecode.sli4j', name: 'sli4j-slf4j-log4j', version: '2.0') { transitive = false }

    implementation(group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.1') { transitive = false }
    implementation(group: 'org.apache.httpcomponents', name: 'httpcore-nio', version: '4.1') { transitive = false }

    implementation(group: 'net.sf.jasperreports', name: 'jasperreports', version: '5.2.0') { transitive = false }
    implementation(group: 'net.sf.jasperreports', name: 'jasperreports-fonts', version: '4.0.0') { transitive = false }

    implementation(group: 'com.google.code.gson', name: 'gson', version: '2.8.5') { transitive = false }

    implementation(group: 'com.google.guava', name: 'guava', version: '30.0-jre') { transitive = false }
    implementation(group: 'com.google.guava', name: 'failureaccess', version: '1.0.1') { transitive = false }

    implementation(group: 'com.github.spullara.mustache.java', name: 'compiler', version: '0.9.7') { transitive = false }

    implementation(group: 'org.eclipse.jetty', name: 'jetty-server', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-util', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-continuation', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-http', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-io', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-servlet', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-servlets', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-security', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-webapp', version: "${jettyVersion}") { transitive = false }
    //implementation(group: 'org.eclipse.jetty', name: 'jetty-jsp', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-runner', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-xml', version: "${jettyVersion}") { transitive = false }
    implementation(group: 'org.eclipse.jetty', name: 'jetty-annotations', version: "${jettyVersion}") { transitive = false }

    implementation(group: 'org.glassfish', name: 'javax.servlet', version: '3.1.1') { transitive = false }
    implementation(group: 'javax.mail', name: 'mail', version: '1.4.7') { transitive = false }
    implementation(group: 'net.lingala.zip4j', name: 'zip4j', version: '1.3.2') { transitive = false }
    implementation(group: 'groovy', name: 'groovy-all', version: '1.1-rc-1') { transitive = false }

    implementation 'com.neuronrobotics:nrjavaserial:5.2.1'
}

jar {
    enabled = true
    archiveFileName = archivesBaseName + '.jar'

    entryCompression ZipEntryCompression.STORED
    manifest {
        attributes(
                'Manifest-Version': '1.0',
                'Class-Path': configurations.runtimeClasspath.collect { "lib/$it.name" }.join(' '),
                'Main-Class': 'ru.apertum.qsystem.Admin',
                'Launcher-Agent-Class': 'ru.apertum.qsystem.extra.Agent',
                'Agent-Class': 'ru.apertum.qsystem.extra.Agent',
                'Premain-Class': 'ru.apertum.qsystem.extra.Agent'
        )
    }
}


//*****************************************************************************
//******   MAKE DISTRIB   *****************************************************
//*****************************************************************************

task copyDeps(type: Copy) {
    from configurations.runtimeClasspath
    into 'dist/lib/'
}

task copylibs(type: Copy) {
    dependsOn copyDeps
    dependsOn jar
    from 'build/libs'
    into 'dist/'
}

// зависимости выполняются по алфавиту по ходу.
task acls() {
    doFirst {
        println 'remove temp folders... '
        delete 'build', 'dist', 'out'
        delete './installation/install.jar'
    }
}
clean.dependsOn(acls)

task bzip(type: Zip) {
    File f = new File(version_properties_file)
    if (f.exists()) {
        from './readme/'
        include 'readme_rus.txt', 'readme_eng.txt', 'readme_spa.txt', 'readme_astra-linux.txt'
        from './installation/'
        include 'install.jar'
        from './installation/resource/txt/'
        include 'install.bat', 'install.sh'
        Properties props = new Properties()
        props.load(new FileInputStream(f))
        archiveFileName = 'qsystem-' + props.version + '.zip'
        destinationDirectory = file('./building/')
    }

    doLast {
        println 'ZIP: ' + destinationDirectory.get().asFile.toString() + '\\' + archiveFileName.get()
    }
}

// выполнить этот таск чтобы все пересобрать и собрать инсталяху. Сборка инсталяхи будет подтянутыми из m2 библиотеками.
task distrib() {

    doFirst {
        println 'run izPack... '
        izPackCreateInstaller.start()
    }

    doLast {
        println 'CI: Install package has been created!'
    }
}

// выполнить этот таск distrib чтобы все пересобрать и собрать инсталяху.
distrib.dependsOn(acls)
distrib.dependsOn(build)
distrib.dependsOn(test)
distrib.dependsOn(copylibs)
distrib.finalizedBy(bzip)
